package com.ruiysoft.controller.anchor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.ruiysoft.entity.statistics.ShopUserStatistics;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.service.statistics.IShopUserStatisticsService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import com.ruiysoft.util.NumberUtils;
import com.ruiysoft.util.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

@Aspect
@Component(value = "anchorAspect")
public class AnchorAspect {
    private Logger logger = LoggerFactory.getLogger(AnchorAspect.class);

    private final IShopUserStatisticsService shopUserStatisticsService;

    @org.springframework.beans.factory.annotation.Autowired
    public AnchorAspect( IShopUserStatisticsService shopUserStatisticsService) {
        this.shopUserStatisticsService = shopUserStatisticsService;
    }

    @Pointcut("@annotation(com.ruiysoft.controller.anchor.Anchor)")
    public void anchor(){    }
    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }
    private Long getUserId() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        return personnel.getId();
    }
    @AfterReturning(value = "anchor()", returning = "retVal")
    public void anchor(JoinPoint joinPoint, Object retVal) {
        logger.debug("进入anchorAspect");
        Long shopId = null;
        Long userId = null;
        try{
            userId = getUserId();
            shopId = getShopId();
        }catch (Exception e){
            logger.error("anchorAspect未获取登录信息",e);
            return;
        }
        // 获取参数
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] parameterNames = methodSignature.getParameterNames();
        Class[] parameterTypes = methodSignature.getParameterTypes();
        Object[] args = joinPoint.getArgs();
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        Class<?> targetClass = joinPoint.getTarget().getClass();
        Method method = null;
        for (Method mt : targetClass.getMethods()) {
             if (methodName.equals(mt.getName())) {
                 method = mt;
                 break;
             }
         }
        if(method==null){
            logger.debug("anchorAspect未获取到method");
             return;
         }
        Anchor anchor = method.getAnnotation(Anchor.class);
        if(Objects.isNull(anchor)){
            logger.debug("anchorAspect未获取到anchor");
            return;
        }
        try {
            Long skuId = null;
            String skuIdStr = anchor.skuId();
            if(StringUtils.isNotBlank(skuIdStr)&& skuIdStr.contains("#")){
                int index = Arrays.binarySearch(parameterNames,skuIdStr.replace("#",""));
                if(index>=0){
                    Object obj = args[index];
                    skuId = TypeUtils.castToLong(obj);
                }
            }else if(StringUtils.isNotBlank(skuIdStr)&& NumberUtils.isLong(skuIdStr)){
                skuId = Long.parseLong(skuIdStr);
            }
            HttpServletRequest request = getHttpServletRequest();
            String ip = RequestUtil.getIPAddr(request);
            String device = request.getHeader("User-Agent");
            shopUserStatisticsService.insertAsyc(new ShopUserStatistics().setInTime(new Date()).setType(anchor.anchorType().getIndex()).setShopId(shopId).setUserId(userId).setSkuId(skuId).setIp(ip).setOrigin(device));
        }catch (Exception e){
            logger.error("保存用户记录错误--{}--{}--{}",JSONObject.toJSONString(anchor),userId,shopId,e);
        }
    }
    @AfterThrowing(value = "anchor()", throwing = "ex")
    public void anchor(JoinPoint joinPoint, Throwable ex) {
    }


    private HttpServletRequest getHttpServletRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }
}
